package cn.tianyigps.obd.handler;

import cn.tianyigps.obd.Storer;
import cn.tianyigps.obd.utils.MessageCoding;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created with IDEA
 *
 * @description: 分包逻辑
 *
 * @author: cui.guibin
 *
 * @create: 2019/3/8 14:28
 **/
@Slf4j
public class EquipmentDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        Object translation = translation(byteBuf);
        if (null == translation){
            list.add(translation);
        }
        channelHandlerContext.fireChannelRead(byteBuf);
    }
    /**
     * 对 报文中的7D01 和7D02 进行转译处理。
     * @param: ByteBuf bf
     * @return Object
     * @author cui.guibin
     * @date 2019/6/5 10:48
     */
    private Object translation(ByteBuf bf) {
        byte[] bytes = MessageCoding.getBytes(bf);
        String strData = MessageCoding.bytesToHexString(bytes);
        String translationStr = strData;
        if (strData.toUpperCase().contains("7D01")){
            translationStr = strData.replace("7D01","7D");
        }
        if (strData.toUpperCase().contains("7D02")){
            translationStr = strData.replace("7D01","7E");
        }
        if (!strData.equals(translationStr)) {
//            Storer.store2Disk(strData,"before","D:/log3.txt");
//            Storer.store2Disk(translationStr,"after ","D:/log3.txt");
            bf.writeBytes(MessageCoding.hexStringToBytes(translationStr));
        }
        return bf;
    }

}
